package com.redis.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * packageName com.redis.controller
 * https://mp.weixin.qq.com/s/IXCC6QFr3ZehY8OY4pP6HA
 * 注意文档里面的命令行，空格要换，还有union week:rank 7 day:1...day:8命令行也是有问题的要换成Zunionstore week:rank 7 day:1...day:8
 * @author chenjie
 * @version JDK 8
 * @className SortController (此处以class为例)
 * @date 2024/9/23
 * @description TODO
 */
@RestController
@RequestMapping("/sort")
public class SortController {
    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping("/zIncrementScore")
    public String zIncrementScore(){
        //db修改数量
        //redis 新增数量
        redisUtil.zIncrementScore("{day:rank}:20240917", 2, 1L);
        Set<ZSetOperations.TypedTuple<Object>> zSetRank = redisUtil.getZSetRank("\"{day:rank}:20240917\"", 0, -1);
        System.out.println(zSetRank);
        String  newkey  =  "{day:rank}";
        List<String> otherKeys  =  new ArrayList<>();
        for  (int  i  =  -6;  i  <  0;  i++)  {
            String  temp  =  "{day:rank}:"  +  DateUtil.format(DateUtil.offsetDay(new Date(),  i),  DatePattern.PURE_DATE_FORMAT);
//              temp=wrapWithBraces(temp);
            otherKeys.add(temp);
        }
        String destkey = "{day:rank}:" + DateUtil.format(new  Date(), DatePattern.PURE_DATE_FORMAT) ;
        redisUtil.zUnionAndStore(destkey,  otherKeys,  newkey);
        return "success";
    }
    @RequestMapping("/querySort")
    public ArrayList<Map> querySort(){
        Set<ZSetOperations.TypedTuple<Object>> zSetRank = redisUtil.getZSetRank("{day:rank}", 0, -1);
        System.out.println(zSetRank);
        //便利
        ArrayList<Map>maps=new ArrayList<>();
        for (ZSetOperations.TypedTuple<Object> typedTuple : zSetRank) {
            //创建Map
            HashMap<String,Object>map=new HashMap<> ();
            Object post_id=typedTuple.getValue();
            String PostHashKey="{rank:post}:"+post_id;
            map.put("id",post_id);
            map.put("title",redisUtil.hget(PostHashKey,"post:title"));
            map.put("commentCount",typedTuple.getScore());
            maps.add(map);
        }

        return maps;
    }


    @RequestMapping("/remove")
    public Integer remove(){

        redisUtil.remove("www",  222);
        Set<ZSetOperations.TypedTuple<Object>> zSetRank = redisUtil.getZSetRank("www", 0, -1);

        return zSetRank.size();
    }

}
